import axios from "../../utils/axios";
const app = getApp();
Page({
  data: {
    isLogin: false,
    isPhoneBtn: false,
    userInfo: [],
    isFeedBackShow: false,
    isBindChildren: false,
    bindCode: null,
    isCoach: false,
  },
  onLoad: async function (options) {
    // if (wx.getStorageSync('token')) {
    // 	console.log(wx.getStorageSync('token'))
    // }
    // await this.login()
  },
  onReady: function () {},
  onShow: async function () {
    if (!wx.getStorageSync("token")) await this.login();
  },
  onHide: function () {},
  // 登录
  async login(e) {
    wx.showLoading({
      title: "登陆中...",
      duration: 1500,
    });
    try {
      let setting = await wx.getSetting();
      if (setting.authSetting["scope.userInfo"]) {
        let loginCodeRes = await wx.login();
        let loginRes = await axios({
          url: "/auth/wx/{appid}/login",
          data: {
            code: loginCodeRes.code,
          },
        });
        console.log("loginRes", loginRes);
        // 判断教练
        if (loginRes.data.user.roles.indexOf("coach") != -1)
          this.setData({
            isCoach: true,
          });
        if (loginRes.data.wxUser.avatarUrl === null) {
          // 如果是第一次登录
          let userInfo = await wx.getUserInfo({
            withCredentials: true,
          });
          // 保存用户数据
          await axios({
            url: "/wx/user/{appid}/info",
            method: "put",
            data: {
              encryptedData: userInfo.encryptedData,
              iv: userInfo.iv,
              rawData: userInfo.rawData,
              signature: userInfo.signature,
              id: loginRes.data.wxUser.id,
              openId: loginRes.data.wxUser.openId,
              sessionKey: loginRes.data.wxUser.sessionKey,
            },
            header: {
              Authorization: loginRes.data.token,
            },
          });
        } else if (loginRes.data.wxUser.phoneNumber === null) {
          // 判断手机号
          this.setData({
            isPhoneBtn: true,
          });
        } else {
          this.setData({
            isLogin: true,
          });
        }
        wx.setStorageSync("token", loginRes.data.token);
        delete loginRes.data.token;
        this.setData({
          userInfo: loginRes.data,
        });
        app.globalData.userInfo = Object.assign(this.data.userInfo.wxUser); // 全局userInfo
      } else console.log("请先授权");
    } catch (error) {
      console.log("登录有错误：", error);
    }
    wx.hideLoading();
  },
  // getphonenumber
  async getphonenumber(e) {
    // 调用接口
    let res = await axios({
      url: "/wx/user/{appid}/phone",
      method: "PUT",
      data: {
        encryptedData: e.detail.encryptedData,
        iv: e.detail.iv,
        openId: this.data.userInfo.wxUser.openId,
        sessionKey: this.data.userInfo.wxUser.sessionKey,
      },
      header: {
        Authorization: wx.getStorageSync("token"),
      },
    });
    console.log("phone", res);
    this.setData({
      isPhoneBtn: false,
      isLogin: true,
    });
  },
  // 跳转
  async navigationTo(e) {
    let curPage = "";
    // let url = '';
    switch (e.currentTarget.dataset.data) {
      case "购物车":
        curPage = "shoppingCar";
        break;
      case "余额":
      case "优惠券":
        curPage = "wallet";
        break;
      case "待付款":
      case "待发货":
      case "待签收":
      case "售后":
        curPage = "orders";
        break;
      case "成长数据":
        curPage = "userInfo";
        break;
      case "联系竞彪":
        curPage = "companyInfo";
        break;
      case "我要反馈":
        curPage = "feedBack";
        break;
      case "我的课堂":
        curPage = "myClass";
        break;
      case "教练课程管理":
        curPage = "classMange";
        break;
      // default:
      //   curPage = 'bug';
    }
    // 判断绑定小孩
    if (curPage == "userInfo" || curPage == "myClass") {
      let res = await axios({
        url: "/api/school/student/hasChild",
        method: "post",
        header: {
          Authorization: wx.getStorageSync("token"),
        },
      });
      if (!res.data) {
        this.setData({
          isBindChildren: true,
        });
        return;
      }
    }

    wx.navigateTo({
      url: `./detail/${curPage}/${curPage}`,
      success: (res) => {
        console.log("跳转成功", res);
      },
      fail: (err) => {
        console.log(err, e.currentTarget.dataset.data);
      },
    });
  },
  feedBack() {
    this.setData({
      isFeedBackShow: !this.data.isFeedBackShow,
    });
  },
  async bindChildren(e) {
    let phoneNumber, bingCode;
    phoneNumber = phoneNumber = app.globalData.userInfo.phoneNumber;
    bingCode = this.data.bindCode;

    let res = await axios({
      url: `/api/school/student/bindStudent/${phoneNumber}/${bingCode}`,
      method: "post",
      header: {
        Authorization: wx.getStorageSync("token"),
      },
    });

    console.log("绑定", res.data);
    // 绑定提示
    wx.showToast({
      title: `绑定${res.data.status ? "成功" : "失败"}`,
      duration: 1500,
      mask: false,
    });
    // 清除数据
    this.setData({
      bindCode: null,
    });
  },
  showBindChindren() {
    this.setData({
      isBindChildren: true,
    });
  },
  changeBindCode(e) {
    let bindCode = e.detail.value;
    this.setData({
      bindCode,
    });
  },
  onBindCodeClose() {
    this.setData({ isBindChildren: false });
  },
});
